package yx.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import yx.dao.BaseDaoInt;
import yx.model.SmCode;
import yx.vo.CodeVO;
import yx.vo.DatagridVO;

@Service("codeService")
public class CodeServiceImpl implements CodeServiceInt {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CodeServiceImpl.class);

	private BaseDaoInt<SmCode> codeDao;

	public BaseDaoInt<SmCode> getCodeDao() {
		return codeDao;
	}

	@Autowired
	public void setCodeDao(BaseDaoInt<SmCode> codeDao) {
		this.codeDao = codeDao;
	}

	@Override
	public CodeVO save(CodeVO code) {
		SmCode t = new SmCode();
		BeanUtils.copyProperties(code, t);
		codeDao.save(t);
		BeanUtils.copyProperties(t, code);
		return code;
	}

	@Override
	public DatagridVO datagrid(CodeVO code) {
		DatagridVO dg = new DatagridVO();
		String hql = "from SmCode t where 1 = 1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(code, hql, params);
		String totalHql = "select count(*) " + hql;
		hql = addOrder(code, hql);
		List<SmCode> l = codeDao.find(hql, params, code.getPage(), code.getRows());
		List<CodeVO> nl = new ArrayList<CodeVO>();
		changeModel(l, nl);
		dg.setTotal(codeDao.count(totalHql, params));
		dg.setRows(nl);
		return dg;
	}

	private void changeModel(List<SmCode> l, List<CodeVO> nl) {
		if (l != null && l.size() > 0) {
			for (SmCode t : l) {
				CodeVO u = new CodeVO();
				BeanUtils.copyProperties(t, u);
				nl.add(u);
			}
		}
	}

	private String addOrder(CodeVO code, String hql) {
		if (code.getSort() != null || code.getOrder() != null) {
			hql += " order by " + code.getSort() + " " + code.getOrder();
		}
		return hql;
	}

	private String addWhere(CodeVO code, String hql, Map<String, Object> params) {
		if (code.getCtype() != null && !"".equals(code.getCtype().trim())) {
			hql += " and t.ctype = :ctype";
			params.put("ctype", code.getCtype());
		}
		return hql;
	}

	@Override
	public void remove(String ids) {
		String[] nids = ids.split(",");
		String hql = "delete SmCode t where t.id in (";
		for (int i = 0; i < nids.length; i++) {
			if (i > 0) {
				hql += ",";
			}
			hql += "'" + nids[i] + "'";
		}
		hql += ")";
		codeDao.executeHql(hql);
	}

	@Override
	public CodeVO edit(CodeVO code) {
		SmCode t = codeDao.get(SmCode.class, code.getId());
		BeanUtils.copyProperties(code, t);
		return code;
	}

}
